import {useState} from "react";
import storage from "./firebase";
import {ref, uploadBytesResumable, getDownloadURL, getStorage} from "firebase/storage";
import {initializeApp} from "firebase/app";
import {Button, Modal, Upload, UploadFile, UploadProps} from "antd";
import {UploadOutlined} from "@ant-design/icons";
import {RcFile} from "antd/es/upload";

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = (error) => reject(error);
    });
const App = (props) => {
    const {setUrl, initValue} = props;

    // State to store uploaded file
    var dd = [];
    if (typeof initValue != "undefined") {
        dd = [{
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: initValue,
        }]
    }
    const [file, setFile] = useState<UploadFile[]>(dd);

    // progress
    const [percent, setPercent] = useState(0);

    // Handle file upload event and update state

    const handleUpload: UploadProps['customRequest'] = async ({file, onError, onProgress, onSuccess}) => {
        try {

            var fileName = (file.uid + "_" + file.type).replace(new RegExp("/", 'g'),"");
            const storageRef = ref(storage, `/images3/${fileName}`);
            // const BlobFile = rcFileToBlob(file)
            // progress can be paused and resumed. It also exposes progress updates.
            // Receives the storage reference and the file to upload.
            const uploadTask = uploadBytesResumable(storageRef, file);

            uploadTask.on(
                "state_changed",
                (snapshot) => {
                    const percent = Math.round(
                        (snapshot.bytesTransferred / snapshot.totalBytes) * 100
                    );
                    // update progress
                    onProgress?.({percent});
                },
                (err) => {
                    onError?.(err);
                    console.log("upload error",err)
                },
                () => {
                    // download url
                    getDownloadURL(uploadTask.snapshot.ref).then((url) => {
                        onSuccess?.({
                            ...file,
                            url
                        });
                        // setUrl(url);
                    });
                }
            );
        } catch (error) {
            console.log(error);

        }
    };

    function rcFileToBlob(rcFile: RcFile) {
        return new Blob([rcFile], {type: rcFile.type});
    }

    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const handleCancel = () => setPreviewOpen(false);
    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };

    return (
        <>
            <Upload
                fileList={file}
                listType={"picture-card"}
                onPreview={handlePreview}
                onChange={({file, fileList}) => {
                    console.log(7788,file);
                    setFile(fileList);
                    if (fileList.length > 0) {
                        fileList.map(f => {
                            if (f.percent == 100 && typeof f.response != "undefined") {
                                setUrl(f.response.url);
                            }
                        })

                    } else {
                        setUrl(null);
                    }
                }}
                multiple
                customRequest={handleUpload}
            >
                {file.length >= 1 ? null : <Button icon={<UploadOutlined/>}> Upload</Button>}

            </Upload>
            <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
                <img alt="example" style={{ width: '100%' }} src={previewImage} />
            </Modal>
        </>
    );
}

export default App;